/* eslint-disable */
<template>
  <a-modal
    :visible="visible"
    :width="900"
    :mask-closable="false"
    @ok="handleModalOk"
    :hideCancel="true"
    @cancel="handleCancel"
  >
    <template #title> 地图 </template>
    <div class="inputWrapper">
      <a-select
        v-model="selectVal"
        placeholder="请输入位置关键字"
        @search="handleSearch"
        :loading="loading"
        :filter-option="false"
        allow-search
      >
        <a-option
          @click="handleChange(item.id)"
          v-for="item in addressList"
          :key="item.id"
          :value="item.id"
          >{{ item.name }}</a-option
        >
      </a-select>
    </div>

    <div id="txMapContainer"></div>
  </a-modal>
</template>

<script setup>
  import { ref, watch, onMounted, getCurrentInstance, toRaw } from 'vue';
  const { proxy } = getCurrentInstance();
  const emits = defineEmits(['confrimHandler', 'update:modelValue']);

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    lnglat: {
      type: Array,
      default: () => [],
    },
  });

  const selectVal = ref('');
  const addressList = ref([]);

  const allMarker = ref([]);

  let map = null;

  const loading = ref(false);

  let timer = null;

  const visible = ref(false);

  const multiple = ref(true);

  watch(
    () => props.modelValue,
    (n) => {
      visible.value = n;
      if (n) {
        proxy.$nextTick(() => {
          initHandler();
        });
      }
    }
  );
  let autoComplete = null;

  const searchListByInput = (val) => {
    autoComplete.search(val, (status, result) => {
      loading.value = false;
      // 搜索成功时，result即是对应的匹配数据
      addressList.value = (result.tips || []).filter((v) => v.id && v.location);
    });
  };

  const handleSearch = (val) => {
    multiple.value = false;
    addressList.value = [];
    clearTimeout(timer);
    timer = setTimeout(() => {
      loading.value = true;
      searchListByInput(val);
    }, 200);
  };

  const addressInfo = ref({});

  let Geocoder = null;

  const clearRecord = () => {
    selectVal.value = '';
    addressList.value = [];
    map?.remove?.(allMarker.value);
  };

  const handleCancel = () => {
    emits('update:modelValue', false);
  };

  const handleChange = (val) => {
    addressInfo.value = addressList.value.find((v) => v.id === val);

    console.log(addressInfo.value);

    map.setZoomAndCenter(16, [
      addressInfo.value.location.lng,
      addressInfo.value.location.lat,
    ]);

    map?.remove?.(allMarker.value);
    allMarker.value = [];
    const marker = new AMap.Marker({
      // eslint-disable-line
      position: new AMap.LngLat( // eslint-disable-line
        addressInfo.value.location.lng,
        addressInfo.value.location.lat
      ), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
      title: addressInfo.value.address,
    });
    allMarker.value.push(marker);
    map.add(marker);
  };

  const handleModalOk = () => {
    emits('confrimHandler', toRaw(addressInfo.value));
  };

  const initDafaultAddress = () => {
    if (props.lnglat.length > 0 && props.lnglat[0]) {
      Geocoder.getAddress(props.lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          const time = new Date().getTime();
          addressList.value = [
            {
              id: time,
              name: result.regeocode.formattedAddress,
              district: result.regeocode.formattedAddress,
              address: '',
              adcode: result.regeocode.addressComponent.adcode,
              location: {
                lat: props.lnglat[1],
                lng: props.lnglat[0],
              },
            },
          ];
          selectVal.value = time;
          handleChange(time);
        }
      });
    } else {
      map?.remove?.(allMarker.value);
    }
  };

  const mapClickHandler = () => {
    map.on('click', (ev) => {
      let url = `${window.location.protocol}//api.tianditu.gov.cn/geocoder?postStr={'lon':${ev.lnglat.lng},'lat':${ev.lnglat.lat},'ver':1}&type=geocode&tk=6040d4c1a269b40b2d3d5683ae6c4bc5`;
      fetch(url).then((response) => {
        if (response.ok) {
          return response.json();
        }
      }).then(res => {
        console.log('====================================');
        console.log(res);
        console.log('====================================');
        const time = new Date().getTime();
          addressList.value = [
            {
              id: time,
              name: result.regeocode.formattedAddress,
              district: result.regeocode.formattedAddress,
              address: '',
              adcode: result.regeocode.addressComponent.adcode,
              location: {
                lat: ev.lnglat.lat,
                lng: ev.lnglat.lng,
              },
            },
          ];
          selectVal.value = time;
          handleChange(time);
      })
    });
  };

  const initHandler = () => {
    map = new T.Map('txMapContainer');
    let zoom = 12;
    map.centerAndZoom(new T.LngLat(116.40769, 39.89945), zoom);
    // const autoOptions = {};
    // Geocoder = new AMap.Geocoder(autoOptions); // eslint-disable-line
    // initDafaultAddress();
    // autoComplete = new AMap.AutoComplete(autoOptions); // eslint-disable-line
    mapClickHandler();
  };

  defineExpose({
    clearRecord,
    initHandler,
  });
</script>

<style lang="less" scoped>
  .inputWrapper {
    margin-bottom: 20px;
  }
  #txMapContainer {
    width: 100%;
    height: 400px;
  }
</style>
